﻿using System;
using UnityEngine;
namespace HBFramework
{
    /// <summary>
    /// 时间管理
    /// </summary>
    public partial class TimeManager : Singleton<TimeManager>, ISingleton, ISingletonUpdate
    {
        int ISingletonUpdate.Order => 0;

        /// <summary>
        /// 本地时间
        /// </summary>
        public DateTime LocalTime => DateTime.Now.AddSeconds(Offset);
        /// <summary>
        /// 网络时间
        /// </summary>
        public DateTime NetwrokTime
        {
            get
            {
                var span = Time.realtimeSinceStartup - lastSyncTime;
                span += Offset;
                return syncTime.AddSeconds(span);
            }
        }
        /// <summary>
        /// 时间偏移
        /// </summary>
        public float Offset { get; set; }

        /// <summary>
        /// 同步间隔
        /// </summary>
        public float SyncInterval
        {
            get => syncInterval;
            set => syncInterval = Mathf.Max(5, value);
        }
        private float syncInterval = 5f;

        /// <summary>
        /// 时间同步事件
        /// </summary>
        public event Action<bool, DateTime> OnTimeSync;

        private DateTime syncTime;
        private float lastSyncTime;
        private bool isSyncing;

        void ISingleton.OnInit()
        {

        }

        void ISingletonUpdate.OnUpdate()
        {
            //SyncNetworkTime();
        }

        void ISingleton.OnDestroy()
        {

        }
    }

    public partial class TimeManager
    {
        /// <summary>
        /// 同步网络时间
        /// </summary>
        public void SyncNetworkTime()
        {
            if (Time.realtimeSinceStartup - lastSyncTime < syncInterval)
            {
                return;
            }
            if (isSyncing) return;
            isSyncing = true;
            NetworkTimeUtility.GetNetworkTime((b, time) =>
            {
                if (b)
                {
                    lastSyncTime = Time.realtimeSinceStartup;
                    syncTime = time;
                }
                OnTimeSync?.Invoke(b, time);
                isSyncing = false;
            });
        }

        public float Now()
        {
            return Time.time;
        }
    }
}